<?php

namespace pmvc\mvc\view;

use pmvc\ioc\ObjectFactory;
use pmvc\ioc\InitializingObject;
use pmvc\mvc\ViewHandlerMapping;
use pmvc\mvc\ViewHandler;
use pmvc\mvc\Request;
use pmvc\util\StringUtil;
use pmvc\util\ClassUtil;
use pmvc\log\Log;
use Exception;

class RegexViewHandlerMapping
	implements InitializingObject,
	ViewHandlerMapping {
		
	public $regexMap;

	private $objectFactory;

	public function initialize(ObjectFactory $objectFactory) {
		$this->objectFactory = $objectFactory;
	}

	public function getViewHandler($viewName, Request $request) {
		foreach ($this->regexMap as $key => $val) {
			if (StringUtil::matches($key, $viewName, FALSE)) {
				$obj = (is_string($val))
					? $this->objectFactory->getObjectById($val)
					: $val;
				if (!ClassUtil::isInstance($obj, 'pmvc\mvc\ViewHandler')) {
					Log::error("Object for mapping {} is not a ViewHandler", $key);
					throw new Exception("Object is not an instance of ViewHandler");
				}
				return $obj;
			}
		}
	}
}

?>